package com.twu.biblioteca;

import java.io.PrintStream;
import java.util.LinkedHashMap;

public class BibliotecaApp {
    private PrintStream ps;
    private Library library;
    private UserQueryHandler query;
    private LinkedHashMap<String, Command> menu;

    public BibliotecaApp(PrintStream ps){
        this(ps, new Library());
    }

    public BibliotecaApp(PrintStream ps, Library library)
    {
        this.ps = ps;
        this.library = library;
        constructDefaultLibrary();
        constructQuery();
        constructMenu();
    }

    public static void main(String[] args) {
        new BibliotecaApp(System.out).run();
    }

    public void run(){
        printWelcome();
        do {
            printMenu();
            int commandNumber = query.userForInt("Please select an option: ");
            select(commandNumber);
        }while(true);
    }

    public void printWelcome(){
        ps.println("Welcome to the Biblioteca!");
    }

    public void printMenu(){
        int optionNumber=1;
        for(String menuItem : menu.keySet()){
            printMenuItem(optionNumber++, menuItem);
        }
    }

    public void select(int selection){
        int index = 1;
        for(Command command : menu.values())
            if(selection == index++)
            {
                command.run();
                return;
            }
        ps.println("Select a valid option!");
    }

    public void printMenuItem(int index, String menuItem){
        ps.print(index + ". ");
        ps.println(menuItem);
    }

    public void constructDefaultLibrary(){
        Book[] defaultListOfBooks =
             {
                 new Book("Crime and Punishment"),
                 new Book("The Brothers Karamazov"),
                 new Book("The Idiot"),
                 new Book("The Double"),
                 new Book("Anna Karenina")
             };
        library.add(defaultListOfBooks);
    }

    public void constructMenu(){
        menu = new LinkedHashMap<String, Command>();
        menu.put("View all books", new ViewBooksCommand(library));
        menu.put("Reserve a book", new ReserveBookCommand(library, query, ps));
        menu.put("Check membership", new CheckMembershipCommand(library, ps));
        menu.put("Quit", new QuitCommand(ps));
    }

    public void constructQuery(){
        query = new UserQueryHandler(ps, System.in);
    }

}
